﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImageCombinerCore.ExMethod
{
    public static class CollectionExMethod
    {
        public static bool Swap<T>(this IList<T> source, T targetItem, int swapInx)
        {
            return source.Swap(targetItem, source.ElementAt(swapInx));
        }

        public static bool Swap<T>(this IList<T> source, T targetItem, T swapItem)
        {
            bool result = false;
            int targetInx = source.IndexOf(targetItem);
            int swapInx = source.IndexOf(swapItem);

            if (targetInx == swapInx) return true;

            if (targetInx > -1 && swapInx > -1)
            {
                var tmpItem = targetItem;
                source[targetInx] = swapItem;
                source[swapInx] = tmpItem;

                result = true;
            }

            return result;
        }

        public static bool SwapToBefore<T>(this IList<T> source, T swapItem)
        {
            var inx = source.IndexOf(swapItem);
            if (inx == -1 || inx == 0) return false;
            return source.Swap(source[inx - 1], swapItem);
        }

        public static bool SwapToAfter<T>(this IList<T> source, T swapItem)
        {
            var inx = source.IndexOf(swapItem);
            if (inx == -1 || inx == source.Count - 1) return false;
            return source.Swap(source[inx + 1], swapItem);
        }

        public static bool SwapToFirst<T>(this IList<T> source, T swapItem)
        {
            bool result = false;
            if (source.Count > 0)
            {
                result = source.Swap(source[0], swapItem);
            }

            return result;
        }

        public static bool SwapToLast<T>(this IList<T> source, T swapItem)
        {
            bool result = false;
            if (source.Count > 0)
            {
                result = source.Swap(source[source.Count - 1], swapItem);
            }

            return result;
        }

        public static bool MoveToFirst<T>(this IList<T> source, T swapItem)
        {
            bool result = false;
            if (source.Count > 0)
            {
                source.Remove(swapItem);
                source.Insert(0, swapItem);
                result = true;
            }

            return result;
        }

        public static bool MoveToLast<T>(this IList<T> source, T swapItem)
        {
            bool result = false;
            if (source.Count > 0)
            {
                source.Remove(swapItem);
                source.Add(swapItem);
                result = true;
            }

            return result;
        }
    }
}
